<script setup lang="ts">
import { ref } from 'vue'
import { message } from 'ant-design-vue';
import { open as openDir } from '@tauri-apps/api/shell';
import { FolderOutlined, FileOutlined, ArrowUpOutlined, ArrowDownOutlined, EditOutlined } from '@ant-design/icons-vue';
import { open } from '@tauri-apps/api/dialog';
import { readDir, renameFile, BaseDirectory } from '@tauri-apps/api/fs';
import { sendCommand } from '../utils/TauriUtils';
import { formatDate, formatFileSize } from '../utils/utils';

const selectedRowKeys = ref<string[]>([]);
const fileList = ref<FileModel[]>([]);
const showRenameModal = ref(false);
const filePrefix = ref("");
const fileSuffix = ref("");
const trimPrefixNum = ref(0);
const trimSuffixNum = ref(0);

interface FileModel {
    id: string,
    key: string,
    oldName: string,
    name: string,
    ext: string,
    path: string,
    size: number,
    sizeStr: string,
    time: Date,
    editFlag: boolean,
    sortNo: number,
}

const selectDir = async () => {
    const selected: null | string | string[] = await open({
        multiple: true,
        directory: true,
    });
    console.log(selected);
    if (Array.isArray(selected)) {
        selected.forEach(async element => {
            const entries = await readDir(element);
            const fileList = entries.filter(item => !item.children).map(item => item.path);
            const result = await sendCommand("file_meta", { 'path': fileList });
            addFile(result);
        });

    } else if (selected === null) {
        // user cancelled the selection
        console.log("没有选择");
    } else {
        // user selected a single file
        console.log("single");
        // fileList.value.push(selected);
    }
}

const selectFile = async () => {
    const selected: null | string | string[] = await open({
        multiple: true,
    });
    console.log(selected);
    if (Array.isArray(selected)) {
        console.log("array, ", selected);
        const result = await sendCommand("file_meta", { 'path': selected });
        addFile(result);
    } else if (selected === null) {
        // user cancelled the selection
        console.log("没有选择");
    } else {
        // user selected a single file
        console.log("single");
        // fileList.value.push(selected);
    }
}

const addFile = (result: any) => {
    let newArray = result.map((i: any, index: number) => {
        return {
            id: i.id,
            key: i.id,
            oldName: i.name,
            name: i.name,
            ext: i.ext,
            path: i.path,
            size: i.size,
            sizeStr: formatFileSize(i.size),
            time: formatDate(new Date(i.modified_time * 1000)),
            editFlag: false,
            sortNo: index,
        }
    });
    fileList.value.push(...newArray);
}

const deleteFile = (file: FileModel) => {
    console.log("deleteFile: ", file);
    fileList.value = fileList.value.filter(i => i.id != file.id);
}

const onSelectChange = (selectedRowKey: string[]) => {
    console.log('selectedRowKeys changed: ', selectedRowKey);
    selectedRowKeys.value = selectedRowKey;
};

const removeFile = () => {
    fileList.value = [];
}

const columns = [
    {
        title: '文件名',
        dataIndex: 'name',
        key: 'name',
        ellipsis: false
    },
    {
        title: '大小',
        dataIndex: 'sizeStr',
        key: 'sizeStr',
        width: '15%',
    },
    {
        title: '文件类型',
        dataIndex: 'ext',
        key: 'ext',
        width: '10%',
    },
    {
        title: '最后修改时间',
        dataIndex: 'time',
        key: 'time',
        width: '20%',
    },
    {
        title: '操作',
        dataIndex: 'operation',
        width: '15%',
    },
];

const editFileName = async (item: FileModel) => {
    console.log("item: ", item);
    item.name = item.name.trim();
    await sendCommand("rename_file", {
        path: item.path,
        old: item.oldName,
        new: item.name
    });
    item.editFlag = false;

}

const editFileNameCancle = (item: FileModel) => {
    item.editFlag = false;
}

const openFile = async (item: FileModel) => {
    await openDir(item.path);
}

const updateSortNo = (item: FileModel, upFlag: boolean) => {
    let array: FileModel[] = fileList.value;
    let index = array.findIndex(i => i.id == item.id);

    // 往上移动
    if (upFlag && index == 0) {
        return;
    }
    if (!upFlag && index == array.length) {
        return;
    }

    let i = array[index];
    let sortNo = i.sortNo;
    let i0 = array[upFlag ? index - 1 : index + 1];
    i.sortNo = i0.sortNo;
    i0.sortNo = sortNo;
    array.sort((a, b) => a.sortNo - b.sortNo);
    console.log(array);
    fileList.value = array;
}

const renameFile = () => {
    trimPrefixNum.value = 0;
    trimSuffixNum.value = 0;
    filePrefix.value = "";
    fileSuffix.value = "";
    showRenameModal.value = true;
}

const handleOk = (e: MouseEvent) => {
    console.log(e);
    showRenameModal.value = false;
    let newList: FileModel[] = [];
    if (trimPrefixNum.value) {
        newList = fileList.value.map(i => {
            i.name = i.name.substring(trimPrefixNum.value, i.name.length);
            return i;
        });
    }
    if (trimSuffixNum.value) {
        newList = fileList.value.map(i => {
            let name = i.name;
            let index = name.lastIndexOf(".");
            if (index < 0) {
                index = name.length;
            }
            console.log('. index: ', index);
            i.name = name.substring(0, index - trimSuffixNum.value) + name.substring(index);
            return i;
        });
    }
    console.log(newList);
    newList.sort((a,b) => a.name.localeCompare(b.name));
    fileList.value = newList;
};
</script>

<template>

    <div class="renameFile">
        <div class="selectGroupBtn">
            <a-button @click="selectDir" size="large">
                <folder-outlined />
                选择目录
            </a-button>

            <a-button class="selectFileBtn" @click="selectFile" size="large">
                <file-outlined />
                选择文件
            </a-button>

            <a-button class="selectFileBtn" @click="removeFile" size="large">
                <file-outlined />
                全部移除
            </a-button>

            <a-button type="primary" class="selectFileBtn" @click="renameFile" size="large">
                <edit-outlined />
                重命名
            </a-button>
        </div>

        <a-table :columns="columns" :data-source="fileList" bordered :pagination="false" :sticky="true">
            <template #bodyCell="{ column, text, record }">
                <template v-if="column.dataIndex === 'name'">
                    <div v-if="record.editFlag">
                        <a-row type="flex">
                            <a-col flex="auto">
                                <a-input v-model:value="record.name"></a-input>
                            </a-col>
                            <a-col flex="10px"></a-col>
                            <a-col flex="50px">
                                <a-button type="primary" @click="editFileName(record)">修改</a-button>
                            </a-col>
                            <a-col flex="10px"></a-col>
                            <a-col flex="50px">
                                <a-button @click="editFileNameCancle(record)">取消</a-button>
                            </a-col>
                        </a-row>
                    </div>
                    <div v-else>
                        <a-row type="flex">
                            <a-col flex="auto"><a-button type="link" @click="(record.editFlag = true)">{{ text
                            }}</a-button></a-col>
                            <a-col flex="5px"><a-button type="text"
                                    @click="updateSortNo(record, true)"><arrow-up-outlined /></a-button></a-col>
                            <a-col flex="5px"><a-button type="text"
                                    @click="updateSortNo(record, false)"><arrow-down-outlined /></a-button></a-col>
                        </a-row>
                    </div>
                </template>
                <template v-if="column.dataIndex === 'operation'">
                    <a @click="openFile(record)">查看</a>
                    <a-divider type="vertical" />
                    <a-popconfirm title="注意该操作不会实际删除文件?" ok-text="移除" cancel-text="取消" @confirm="deleteFile(record)">
                        <a>移除</a>
                    </a-popconfirm>
                </template>
            </template>

        </a-table>
    </div>

    <a-modal v-model:visible="showRenameModal" width="50%" title="输入规则" @ok="handleOk" cancelText="取消" okText="应用规则">
        <p>去掉前N个字符</p>
        <a-input-number id="inputNumber" v-model:value="trimPrefixNum" :min="0" :max="50" />
        <p style="margin-top: 20px;">去掉后N个字符</p>
        <a-input-number id="inputNumber" v-model:value="trimSuffixNum" :min="0" :max="50" />
        <p style="margin-top: 20px;">自定义前缀，输入:N 表示递增数字</p>
        <a-input size="large" v-model:value="filePrefix" placeholder="自定义前缀" />
        <p style="margin-top: 20px;">自定义后缀，输入:N 表示递增数字</p>
        <a-input size="large" v-model:value="fileSuffix" placeholder="自定义后缀" />

    </a-modal>
</template>

<style scoped>
.renameFile {
    padding: 2%;
}

.selectGroupBtn {
    padding-bottom: 20px;
}

.selectFileBtn {
    margin-left: 20px;
}
</style>
